package handlers

import (
	"k8s-service/models"
	"k8s-service/service"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

var modelConfigService *service.ModelConfigService

// InitModelConfigService 初始化模型配置服务
func InitModelConfigService(dbPath string) error {
	var err error
	modelConfigService, err = service.NewModelConfigService(dbPath)
	return err
}

// CreateModelConfig 创建模型配置
// @Summary 创建模型配置
// @Description 创建新的模型配置信息
// @Tags 模型配置管理
// @Accept json
// @Produce json
// @Param config body models.CreateModelConfigRequest true "模型配置信息"
// @Success 200 {object} models.ModelConfigResponse
// @Failure 400 {object} models.CommonResponse
// @Failure 500 {object} models.CommonResponse
// @Router /model-config [post]
func CreateModelConfig(c *gin.Context) {
	var req models.CreateModelConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, models.CommonResponse{
			Code:    400,
			Message: "请求参数错误: " + err.Error(),
		})
		return
	}

	config, err := modelConfigService.CreateModelConfig(&req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, models.CommonResponse{
			Code:    500,
			Message: err.Error(),
		})
		return
	}

	// 清除代理缓存
	InvalidateProxyCache()

	c.JSON(http.StatusOK, models.ModelConfigResponse{
		Code:    200,
		Message: "创建成功",
		Data:    config,
	})
}

// GetModelConfig 获取模型配置详情
// @Summary 获取模型配置详情
// @Description 根据ID获取模型配置详情
// @Tags 模型配置管理
// @Produce json
// @Param id path int true "配置ID"
// @Success 200 {object} models.ModelConfigResponse
// @Failure 400 {object} models.CommonResponse
// @Failure 404 {object} models.CommonResponse
// @Router /model-config/{id} [get]
func GetModelConfig(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.CommonResponse{
			Code:    400,
			Message: "无效的ID格式",
		})
		return
	}

	config, err := modelConfigService.GetModelConfigByID(id)
	if err != nil {
		statusCode := http.StatusInternalServerError
		if err.Error() == "模型配置不存在" {
			statusCode = http.StatusNotFound
		}
		c.JSON(statusCode, models.CommonResponse{
			Code:    statusCode,
			Message: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, models.ModelConfigResponse{
		Code:    200,
		Message: "获取成功",
		Data:    config,
	})
}

// UpdateModelConfig 更新模型配置
// @Summary 更新模型配置
// @Description 根据ID更新模型配置信息
// @Tags 模型配置管理
// @Accept json
// @Produce json
// @Param id path int true "配置ID"
// @Param config body models.UpdateModelConfigRequest true "更新的配置信息"
// @Success 200 {object} models.ModelConfigResponse
// @Failure 400 {object} models.CommonResponse
// @Failure 404 {object} models.CommonResponse
// @Failure 500 {object} models.CommonResponse
// @Router /model-config/{id} [put]
func UpdateModelConfig(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.CommonResponse{
			Code:    400,
			Message: "无效的ID格式",
		})
		return
	}

	var req models.UpdateModelConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, models.CommonResponse{
			Code:    400,
			Message: "请求参数错误: " + err.Error(),
		})
		return
	}

	config, err := modelConfigService.UpdateModelConfig(id, &req)
	if err != nil {
		statusCode := http.StatusInternalServerError
		if err.Error() == "模型配置不存在" {
			statusCode = http.StatusNotFound
		}
		c.JSON(statusCode, models.CommonResponse{
			Code:    statusCode,
			Message: err.Error(),
		})
		return
	}

	// 清除代理缓存
	InvalidateProxyCache()

	c.JSON(http.StatusOK, models.ModelConfigResponse{
		Code:    200,
		Message: "更新成功",
		Data:    config,
	})
}

// DeleteModelConfig 删除模型配置
// @Summary 删除模型配置
// @Description 根据ID删除模型配置
// @Tags 模型配置管理
// @Produce json
// @Param id path int true "配置ID"
// @Success 200 {object} models.CommonResponse
// @Failure 400 {object} models.CommonResponse
// @Failure 404 {object} models.CommonResponse
// @Failure 500 {object} models.CommonResponse
// @Router /model-config/{id} [delete]
func DeleteModelConfig(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.CommonResponse{
			Code:    400,
			Message: "无效的ID格式",
		})
		return
	}

	err = modelConfigService.DeleteModelConfig(id)
	if err != nil {
		statusCode := http.StatusInternalServerError
		if err.Error() == "模型配置不存在" {
			statusCode = http.StatusNotFound
		}
		c.JSON(statusCode, models.CommonResponse{
			Code:    statusCode,
			Message: err.Error(),
		})
		return
	}

	// 清除代理缓存
	InvalidateProxyCache()

	c.JSON(http.StatusOK, models.CommonResponse{
		Code:    200,
		Message: "删除成功",
	})
}

// ListModelConfigs 获取模型配置列表
// @Summary 获取模型配置列表
// @Description 分页获取模型配置列表，支持按类型和状态筛选
// @Tags 模型配置管理
// @Produce json
// @Param page query int false "页码，默认1" default(1)
// @Param size query int false "每页大小，默认10，最大100" default(10)
// @Param model_type query string false "模型类型筛选" Enums(llm,embedding,reranker)
// @Param enabled query int false "启用状态筛选" Enums(0,1)
// @Success 200 {object} models.ModelConfigListAPIResponse
// @Failure 400 {object} models.CommonResponse
// @Failure 500 {object} models.CommonResponse
// @Router /model-config [get]
func ListModelConfigs(c *gin.Context) {
	// 解析分页参数
	page := 1
	if pageStr := c.Query("page"); pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}

	size := 10
	if sizeStr := c.Query("size"); sizeStr != "" {
		if s, err := strconv.Atoi(sizeStr); err == nil && s > 0 {
			size = s
		}
	}

	// 解析筛选参数
	modelType := c.Query("model_type")

	var enabled *int
	if enabledStr := c.Query("enabled"); enabledStr != "" {
		if e, err := strconv.Atoi(enabledStr); err == nil && (e == 0 || e == 1) {
			enabled = &e
		}
	}

	// 获取列表
	result, err := modelConfigService.ListModelConfigs(page, size, modelType, enabled)
	if err != nil {
		c.JSON(http.StatusInternalServerError, models.CommonResponse{
			Code:    500,
			Message: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, models.ModelConfigListAPIResponse{
		Code:    200,
		Message: "获取成功",
		Data:    result,
	})
}

// GetEnabledModelConfigs 获取所有启用的模型配置
// @Summary 获取启用的模型配置
// @Description 获取所有启用状态的模型配置列表
// @Tags 模型配置管理
// @Produce json
// @Success 200 {object} models.ModelConfigListAPIResponse
// @Failure 500 {object} models.CommonResponse
// @Router /model-config/enabled [get]
func GetEnabledModelConfigs(c *gin.Context) {
	configs, err := modelConfigService.GetEnabledModelConfigs()
	if err != nil {
		c.JSON(http.StatusInternalServerError, models.CommonResponse{
			Code:    500,
			Message: err.Error(),
		})
		return
	}

	result := &models.ModelConfigListResponse{
		Total: len(configs),
		List:  configs,
		Page:  1,
		Size:  len(configs),
	}

	c.JSON(http.StatusOK, models.ModelConfigListAPIResponse{
		Code:    200,
		Message: "获取成功",
		Data:    result,
	})
}

// ToggleModelConfigStatus 切换模型配置启用状态
// @Summary 切换模型配置状态
// @Description 切换指定模型配置的启用/禁用状态
// @Tags 模型配置管理
// @Produce json
// @Param id path int true "配置ID"
// @Success 200 {object} models.ModelConfigResponse
// @Failure 400 {object} models.CommonResponse
// @Failure 404 {object} models.CommonResponse
// @Failure 500 {object} models.CommonResponse
// @Router /model-config/{id}/toggle [post]
func ToggleModelConfigStatus(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.CommonResponse{
			Code:    400,
			Message: "无效的ID格式",
		})
		return
	}

	config, err := modelConfigService.ToggleModelConfigStatus(id)
	if err != nil {
		statusCode := http.StatusInternalServerError
		if err.Error() == "模型配置不存在" {
			statusCode = http.StatusNotFound
		}
		c.JSON(statusCode, models.CommonResponse{
			Code:    statusCode,
			Message: err.Error(),
		})
		return
	}

	// 清除代理缓存
	InvalidateProxyCache()

	statusText := "禁用"
	if config.Enabled == 1 {
		statusText = "启用"
	}

	c.JSON(http.StatusOK, models.ModelConfigResponse{
		Code:    200,
		Message: "已" + statusText,
		Data:    config,
	})
}
